<!--
 * @Author: 颜礼田 2564217790@qq.com
 * @Date: 2024-09-10 11:18:43
 * @LastEditors: MrDotYan 2564217790@qq.com
 * @LastEditTime: 2024-09-27 10:40:52
 * @FilePath: /webServerAdmin/src/views/system/departmentManage/components/edit.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <el-drawer v-model="visible">
    <el-form ref="formRef" :model="modelValue" :rules="rules" label-position="top">
      <el-form-item label="头像">
        <Upload v-model:imageUrl="modelValue.avatar!"></Upload>
      </el-form-item>
      <el-form-item label="用户部门" prop="dept">
        <el-tree-select
          style="width: 100%"
          show-checkbox
          v-model="modelValue.dept!.id"
          :data="deptOpt"
          check-strictly
          node-key="id"
          clearable
          :multiple="false"
          :props="{
            label: 'deptName'
          }"
          :render-after-expand="false"
          check-on-click-node
        />
      </el-form-item>
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="modelValue.userName"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="modelValue.mobile"></el-input>
      </el-form-item>
      <el-form-item v-if="!isNotEmpty(modelValue.id)" label="密码" prop="password">
        <el-input v-model="modelValue.password"></el-input>
      </el-form-item>
      <el-form-item label="身份证号" prop="idCardNo">
        <el-input v-model="modelValue.idCardNo"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="modelValue.email"></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-descriptions style="width: 100%" :column="1" border>
          <template #extra>
            <el-button @click="openRole" type="primary">添加</el-button>
          </template>
          <el-descriptions-item v-for="item of modelValue.role" :key="item.id" label="角色名称">
            {{ item?.roleName ?? "--" }}
          </el-descriptions-item>
        </el-descriptions>
      </el-form-item>
    </el-form>

    <template #footer>
      <div>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
    <Role ref="roleRef" @success="selectedRole"></Role>
  </el-drawer>
</template>

<script lang="ts" setup>
import { fetchDeptTrees } from "@/api/modules/department";
import { editUser, saveUser, fetchUserInfo } from "@/api/modules/user";
import { ResultEnum } from "@/enums/httpEnum";
import { DepartmentSchema, RoleSchema, UserSchema } from "@/schema";
import { EmitProps, RefOpenEventProps } from "@/typings/interface";
import { isNotEmpty } from "@/utils/isHelper";
import { ElNotification, FormInstance } from "element-plus";
import { reactive, watch, nextTick, ref } from "vue";
import Role from "./role.vue";
import Upload from "@/components/Upload/Img.vue";

const visible = ref(false);
const deptOpt = ref<Array<DepartmentSchema>>([]);
const formRef = ref<FormInstance>();
const roleRef = ref<RefOpenEventProps<Array<RoleSchema>>>();

function openRole() {
  roleRef.value?.open(modelValue.role);
}

function selectedRole(selectedList) {
  modelValue.role = selectedList;
}

const modelValue = reactive<UserSchema>({
  userName: "",
  mobile: "",
  dept: { id: "" } as DepartmentSchema,
  idCardNo: "",
  password: "",
  avatar: "",
  email: "",
  role: [] as Array<RoleSchema>
});

const rules = {
  userName: [{ message: "请输入用户名称", trigger: "blur", required: true }],
  password: [{ message: "请输入用户密码", trigger: "blur", required: true }],
  mobile: [{ message: "请输入手机号", trigger: "blur", required: true }],
  "dept.id": [{ message: "请选择部门", trigger: "blur", required: true }],
  idCardNo: [{ message: "请填写身份证号码", trigger: "blur", required: true }],
  role: [{ message: "请选择角色", trigger: "blur", required: true }]
};

function submit() {
  formRef.value?.validate().then(valid => {
    if (valid) {
      if (modelValue.id) {
        edit();
      } else {
        save();
      }
    }
  });
}

const emit = defineEmits<EmitProps>();

function edit() {
  editUser({ id: modelValue.id }, modelValue).then(r => {
    const { code, message } = r;
    if (code === ResultEnum.SUCCESS) {
      visible.value = false;
      emit("success");
      ElNotification.success("添加成功！");
    } else {
      ElNotification.error(message);
    }
  });
}

function save() {
  saveUser(modelValue).then(r => {
    const { code, message } = r;
    if (code === ResultEnum.SUCCESS) {
      visible.value = false;
      emit("success");
      ElNotification.success("编辑成功！");
    } else {
      ElNotification.error(message);
    }
  });
}

defineExpose({
  open(row) {
    visible.value = true;
    if (isNotEmpty(row)) {
      fetchUser(row);
    }
    fetchDeptTree();
  }
});

function fetchDeptTree() {
  fetchDeptTrees().then(r => {
    const { code, data, message } = r;
    if (code === ResultEnum.SUCCESS) {
      deptOpt.value = [];
      deptOpt.value = deptOpt.value.concat(data.list);
    } else {
      ElNotification.error(message);
    }
  });
}

function fetchUser(row) {
  fetchUserInfo({ id: row.id }).then(r => {
    const { code, data, message } = r;
    if (code === ResultEnum.SUCCESS) {
      nextTick(() =>
        Object.assign(modelValue, {
          ...data,
          dept: data?.dept ?? { id: "" }
        })
      );
    } else {
      ElNotification.error(message);
    }
  });
}

watch(
  () => visible.value,
  newVal => {
    if (!newVal) {
      nextTick(() => {
        formRef.value?.resetFields();
        modelValue.dept = { id: "" } as DepartmentSchema;
        modelValue.role = [];
        modelValue.id = "";
        modelValue.avatar = "";
      });
    }
  }
);
</script>
